import UserApi from '@/common/api/UserApi';
import utils from '@/common/utils';
import initialization from '@/common/initialization';
import Router from '@/router'

export let RolesTree =  [];

export default {
	state: {
		menus: [],
		buttons: []
	},
	mutations: {
		SET_MENUS(s, menus) {
			s.menus = menus;
		},
		SET_BUTTONS(s, buttons) {
			s.buttons = buttons;
		}
	},
	actions: {
		async getMenus({commit}) {
			return await UserApi.menu().then(async res => {
				return await utils.responseHandler(res).then(({data}) => {
					if (!data) return false;
					let menus = data.filter(item => item.menuType !== 'button')
					let buttons = data.map(item =>item.perms)
					commit('SET_MENUS', menus)
					commit('SET_BUTTONS', buttons)
					RolesTree = initialization.generateMenuTree(menus);
					let router = initialization.generateRouter(RolesTree);
					Router.addRoute(router)
				})
			})
		}
	},
	getters: {
		menus: s => s.menus,
		buttons: s => s.buttons
	}
}